package com.qianfeng.smartdevices.websocket.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.smartdevices.event.CheckDeviceStatusEvent;
import com.qianfeng.smartdevices.event.PowerCommandEvent;
import com.qianfeng.smartdevices.event.UpdateDeviceStatusEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class PowerCommendHandler extends TextWebSocketHandler {
    private Map<Object, WebSocketSession> allClients = new HashMap<>();

    private ObjectMapper objectMapper;

    private ApplicationContext context;
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        Object name = session.getAttributes().get("name");
        WebSocketSession socketSession = allClients.get(name);
        if(socketSession != null) {
            socketSession.close();
            allClients.remove(name);
        }
        System.err.println("继电器建立了请求===>" + name);
        allClients.put(name,session);
        context.publishEvent(new UpdateDeviceStatusEvent((String) name,"1"));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.err.println("收到设备发出的消息" + message.getPayload());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);

        Object name = session.getAttributes().get("name");
        context.publishEvent(new UpdateDeviceStatusEvent((String) name,"0"));
        allClients.remove(name);
    }
    @EventListener
    @Async
    public void onEvent(PowerCommandEvent event) throws IOException {
        System.err.println(Thread.currentThread().getName());
        String uuid = event.getUuid();
        WebSocketSession socketSession = allClients.get(uuid);
        if (socketSession != null && socketSession.isOpen()) {
            socketSession.sendMessage(new TextMessage(event.getCommand()));
        }
    }
    @EventListener
    @Async
    public void onEvent(CheckDeviceStatusEvent event) {
        allClients.forEach((uuid,session) ->{
            try {
                session.sendMessage(new TextMessage(""));
            } catch (IOException e) {
                e.printStackTrace();

                System.err.println("设备编号为" + uuid + "已经离线了");
                context.publishEvent(new UpdateDeviceStatusEvent((String) uuid, "0"));
                allClients.remove(uuid);
            }
        });


    }
}
